package com.sky.Aspect;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import com.sky.annotation.Limit;
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;

@Component
@Aspect
@Slf4j
public class LimitAop {

    /**
     * 不同的接口，不同的流量控制
     * map的key为 Limiter.key
     */
    private final Map<String, RateLimiter> limitmap = Maps.newConcurrentMap();

    @Around("@annotation(com.sky.annotation.Limit)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        // 拿到Limit注解
        Limit limit = method.getAnnotation(Limit.class);

        if (limit != null){
            // key的作用，不用的接口，不同的流量控制
            String key = limit.key();
            RateLimiter rateLimiter = null;

            // 验证缓存中是否存在null
            if (!limitmap.containsKey(key)) {
                // 创建令牌桶
                rateLimiter = RateLimiter.create(limit.permitsPerSecond());
                limitmap.put(key, rateLimiter);
                log.info("新建了令牌桶={}，容量={}",key,limit.permitsPerSecond());
            }
            rateLimiter = limitmap.get(key);
            // 拿令牌
            boolean acquire = rateLimiter.tryAcquire(limit.timeout(), limit.timeunit());
            if (!acquire) {
                log.debug("令牌桶={}，获取令牌失败",key);
                return Result.error(MessageConstant.SYSTEM_BUSY);
            }
        }
        return proceedingJoinPoint.proceed();
    }

}
